package com.macrounion.atv.task;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import com.macrounion.atv.cache.AlarmCache;
import com.macrounion.atv.cache.AlarmCache.AlarmCacheData;
import com.macrounion.atv.cache.ChannelCache;
import com.macrounion.atv.processor.ChannelProcessor;
import com.macrounion.atv.processor.CurrentDataProcessor;
import com.macrounion.atv.processor.DeviceProcessor;
import com.macrounion.atv.service.entity.Channel;
import com.macrounion.atv.service.entity.Device;

/**
 * 
 * @author Administrator
 *
 */
@Component
public class SaveAlarmsTask {
	@Autowired
	private CurrentDataProcessor currentDataProcessor;
	@Autowired
	private ChannelProcessor channelProcessor;
	@Autowired
	private AlarmCache alarmCache;
	@Autowired
	private DeviceProcessor deviceProcessor;
	@Autowired
	private ChannelCache channelCache;
	
	@Scheduled(cron="${timely.handleAlarm:0/10 * * * * ? }")
	public void handleAlarms() {
		if(alarmCache.isEmpty())
			return;
		AlarmCacheData currentDeviceData = alarmCache.takeOneAlarms();
		if(currentDeviceData!=null && !CollectionUtils.isEmpty(currentDeviceData.getDatas())) {
			Device device = deviceProcessor.findById(currentDeviceData.getDeviceId());
			if(device == null)
				return;
			currentDataProcessor.saveAlarmData(device.getId(),currentDeviceData.getDatas());
    		//存储虚拟通道
			currentDeviceData.getDatas().forEach(d->{
				Channel c = channelCache.getChannel(d.getDeviceId(), d.getChannelCode());
				if(c!=null && StringUtils.isEmpty(c.getVirtualId())) {
					channelProcessor.saveVirtual(device, c);
				}
			});
		}
		if(!alarmCache.isEmpty())
			this.handleAlarms();
	}
	
}
